package com.liangtian.mdm.dm.jsp.util;

// import com.liangtian.mdm.activiti.api.entity.ShForm;
// import com.liangtian.mdm.activiti.api.entity.TjForm;
import com.liangtian.mdm.base.utils.ShiroSessionUtils;
import com.liangtian.mdm.dm.common.constant.TableConst;
import com.liangtian.mdm.dm.common.enums.Flag;
import com.liangtian.mdm.dm.jsp.dao.JspActionDao;
import com.liangtian.mdm.dm.jsp.service.AutoCodeService;
import com.liangtian.mdm.system.business.dao.SysBusinessDao;
import com.liangtian.mdm.system.file.dao.SysFileDao;
import com.liangtian.mdm.system.mdmDis.target.dao.DispatchServiceDao;
import com.liangtian.mdm.system.user.model.SysUser;
import com.liangtian.mdm.util.ConstantBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class SqlUtilSysContent {
    @Autowired
    private JspActionDao jspActionDao;
    @Autowired
    SysFileDao sysFileDao;
    @Autowired
    SysBusinessDao sysBusinessDao;
    @Autowired
    DispatchServiceDao dispatchServiceDao;
    @Autowired
    AutoCodeService autoCodeService;
    // @Autowired
    // SysContentDao sysContentDao;
    //============================标准文档模块操作 ========开始=====================================================================================

    /**
     * 文档新增操作的插入sql----只针对文档操作
     *
     * @param param
     * @return
     */
    public Map<String, Object> genSysContentInsertSql(Map<String, Object> param) {

        String tableName = param.get("tableName").toString();
        StringBuilder sqlHeader = new StringBuilder();
        StringBuilder sqlValues = new StringBuilder();
        sqlHeader.append("insert into ").append(tableName).append("(");
        sqlValues.append("values(");

        //获取session中用户
        SysUser user = ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER);
        Map<String, String> cond = new HashMap<String, String>();
        cond.put("tableSeqNextval", tableName + TableConst.SEQUENCESUFFIX + ".nextval");
        String idValue = jspActionDao.selectIdBySeq(cond);

        sqlValues.append("'").append(idValue).append("', '")
                .append((String) param.get("contentName")).append("', '")
                .append((String) param.get("forumId")).append("', '")
                .append((String) param.get("forumName")).append("', '")
                .append((String) param.get("des")).append("', '")
                .append((String) param.get("contentText")).append("',")
                .append(Flag.STATE_0.getCode()).append(", '")
                .append((String) param.get("important")).append("',")
                .append(" sysdate, '").append(user.getUserId()).append("', '")
                .append(user.getUserName()).append("', '")
                .append((String) param.get("keyWord")).append("', ")
                .append(Flag.STATUS_0.getCode()).append(", '")
                .append("', '").append("', '").append("','").append("','").append("','")
                .append((String) param.get("fileId")).append("','")
                .append("0").append("'");
        sqlHeader.append("CONTENT_ID,CONTENT_NAME,FORUM_ID,FORUM_NAME,DES,CONTENT_TEXT,STATE,IMPORTANT,OPER_TIME,OPER_USER,OPER_UNAME,KEYWORD,STATUS,UPDATE_TIME,UPDATE_USER,UPDATE_UNAME,SUBMIT_TIME,FORUM_NUM,FILE_ID,VERSION)");
        sqlValues.append(") ");

        String sql = sqlHeader.append(sqlValues).toString();
        Map<String, Object> res_Map = new HashMap<>();
        res_Map.put("idValue", idValue);
        res_Map.put("version", "0");
        res_Map.put("sql", sql);
        return res_Map;
    }

    /**
     * <p>TODO 文档审核流程方法 </p>
     * <p>@param form
     * <p>@param isEnd
     * <p>@return </p>
     *
     * @author : xiaoliu
     * @date :2017年5月26日上午9:21:44
     */
//     public List<String> genSysContentFlowApproveSql(ShForm form, boolean isEnd) {
//         String tableName = form.getTableName();
//         String operType = form.getOperType();  //审核、变更、冻结、解冻、新增
//         String dataId = form.getDataId();
//         //生成自动配码
//         StringBuilder val = new StringBuilder();
//         List<String> sqls = new ArrayList<String>();
//         if (isEnd) {
//             //审核通过
//             if (form.isPass()) {
// //				if(Flag.OPER_2.getDesc().equals(operType)){
//                 if (Flag.OPER_2.getCode().equals(operType)) {
//                     sqls.add("update " + tableName + " set state = " + Flag.STATE_4.getCode() + val.toString() + " where content_id = " + dataId);
//                 } else {
//                     sqls.add("update " + tableName + " set state = " + Flag.STATE_4.getCode() + val.toString() + " where content_id = " + dataId);
//                     String contentId = "";
//                     Map<String, Object> map = new HashMap<>();
//                     Map<String, Object> mapconn = new HashMap<>();
//                     if (tableName.endsWith(TableConst.MODIFYSUFFIX)) {//如果是以_UPDATE结束的表
//                         map.put("tableName", tableName);
//                         map.put("contentId", dataId);
//                         Map<String, Object> maptable = sysContentDao.querySysContentUpdateDetail(map);
//                         contentId = (String) maptable.get("orgId");
//                         mapconn.put("tableName", tableName.substring(0, tableName.lastIndexOf("_")));
//                         mapconn.put("contentId", contentId);
//                     } else {
//                         mapconn.put("tableName", tableName);
//                         mapconn.put("contentId", dataId);
// //						 contentId = String.valueOf(dataId);
//                     }
//
//                     //当前数据详细信息
//
//                     Map<String, Object> current = sysContentDao.querySysContentDetail(mapconn);
//                     //版本
//                     String version = String.valueOf(current.get("version")) == null ? "0" : String.valueOf(current.get("version")).toString();
//                     //原数据ID
//
//
//                     //原始表
//                     String originTable = tableName.endsWith(TableConst.MODIFYSUFFIX) ? tableName.substring(0, tableName.lastIndexOf("_")) : tableName;
//
//                     //第一次变更
// //					if("1".equals(version)){
// //						StringBuilder sqlHistory = new StringBuilder();
// //						//将原始插入变更
// //
// //						sqlHistory.append("insert into ").append(tableName)
// //							.append("(").append(" CONTENT_ID,CONTENT_NAME,FORUM_ID,DES,CONTENT_TEXT,UPDATE_TIME,STATE,IMPORTANT,"
// //									+ "OPER_TIME,OPER_USER,OPER_UNAME,KEYWORD,SUBMIT_TIME,VERSION,ORG_ID,OPERATIONTYPE,OPER_TYPE,FILE_ID,FORUM_NAME )");
// //						sqlHistory.append(" select ")
// //						   .append(tableName).append(TableConst.SEQUENCESUFFIX).append(".nextval,")
// //						   .append("CONTENT_NAME,FORUM_ID,DES,CONTENT_TEXT,UPDATE_TIME,STATE,IMPORTANT,"
// //						   		+ "OPER_TIME,OPER_USER,OPER_UNAME,KEYWORD,SUBMIT_TIME,VERSION,ORG_ID,OPERATIONTYPE,OPER_TYPE,FILE_ID,FORUM_NAME  from ")
// //						   .append(originTable).append(" WHERE CONTENT_ID = ").append(contentId);
// //						//插入最初记录
// //						sqls.add(sqlHistory.toString());
// //					}
//                     //解冻
//                     if (Flag.OPER_4.getCode().equals(operType)) {
//                         sqls.add("update " + originTable + " set status = " + Flag.STATUS_0.getCode() + ", version=version+1 where content_Id = "
//                                 + "(select org_id from " + tableName + " where content_Id =" + dataId + ")");
//                     }
//                     //冻结
//                     else if (Flag.OPER_3.getCode().equals(operType)) {
//                         sqls.add("update " + originTable + " set status = " + Flag.STATUS_1.getCode() + ", version=version+1 where content_Id = "
//                                 + "(select org_id from " + tableName + " where content_Id =" + dataId + ")");
//                     }
//                     //变更
//                     else if (Flag.OPER_1.getCode().equals(operType)) {
//                         //更新原表数据
//                         StringBuilder sqlUpd = new StringBuilder();
//                         sqlUpd.append("update ").append(originTable).append(" set (")
//                                 .append(" CONTENT_NAME,FORUM_ID,DES,CONTENT_TEXT,UPDATE_TIME,STATE,IMPORTANT,"
//                                         + "OPER_TIME,OPER_USER,OPER_UNAME,KEYWORD,SUBMIT_TIME,VERSION,FILE_ID,FORUM_NAME) = ");
//
//                         StringBuilder sqlVal = new StringBuilder();
//                         sqlVal.append("(select ")
//                                 .append(" CONTENT_NAME,FORUM_ID,DES,CONTENT_TEXT,UPDATE_TIME,STATE,IMPORTANT,"
//                                         + "OPER_TIME,OPER_USER,OPER_UNAME,KEYWORD,SUBMIT_TIME,VERSION,FILE_ID,FORUM_NAME from ")
//                                 .append(tableName).append(" where content_Id = ").append(dataId).append(")")
//                                 .append(" where content_id = ").append(contentId);
//                         sqls.add(sqlUpd.append(sqlVal).toString());
//                     }
//                 }
//             } else {
//                 if (Flag.OPER_2.getCode().equals(operType)) {
//                     sqls.add("update " + tableName + " set state = " + Flag.STATE_3.getCode() + " where content_id = " + dataId);
//                 } else {
//                     sqls.add("update " + tableName + " set state = " + Flag.STATE_3.getCode() + " where content_id = " + dataId);
//                 }
//             }
//         }
//         return sqls;
//     }

    /**
     * <p>TODO 标准文档提交方法---标准文档</p>
     * <p>@param form
     * <p>@param needFlow
     * <p>@return </p>
     *
     * @author : xiaoliu
     * @date :2017年5月19日上午10:40:44
     */
    // public List<String> genFlowSubmitSysContentSql(TjForm form, boolean needFlow) {
    //     String tableName = form.getTableName();
    //     String dataId = form.getDataId();
    //
    //     StringBuilder sql = new StringBuilder();
    //     sql.append("update " + tableName + " set state = ");
    //     if (needFlow) {
    //         sql.append(Flag.STATE_5.getCode());
    //     } else {
    //         sql.append(Flag.STATE_4.getCode());
    //     }
    //     sql.append(" where content_id = '").append(dataId).append("'");
    //
    //     List<String> sqls = new ArrayList<String>();
    //     sqls.add(sql.toString());
    //     return sqls;
    // }

    /**
     * 生成变更操作的插入sql--文档管理
     *
     * @param param
     * @return
     */
    public List<String> genSysContentBgInsertSql(Map<String, Object> param, List<String> sqls) {
        //表名
        String tableName = param.get("tableName").toString();
        String originTable = tableName.substring(0, tableName.lastIndexOf("_"));
        String bgId = null;
        if (param.get("bgId") == null) {
            //非主从、主从表-从表
            bgId = tableName + TableConst.SEQUENCESUFFIX + ".nextVal";
            Map<String, String> m = new HashMap<String, String>();
            m.put("tableSeqNextval", bgId);
        } else {
            // 主从表-主表
            bgId = param.get("bgId").toString();
        }

        StringBuilder sql = new StringBuilder();
        sql.append("insert into ").append(tableName).append("(");
        sql.append("CONTENT_ID,ORG_ID,CONTENT_NAME,FORUM_ID,FORUM_NAME,DES,CONTENT_TEXT,UPDATE_TIME,STATE, IMPORTANT,OPER_TIME,OPER_USER,");
        sql.append("OPER_UNAME,KEYWORD,SUBMIT_TIME,VERSION,OPERATIONTYPE,OPER_TYPE,FILE_ID)");
        //获取session中用户
        SysUser user = ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER);
        sql.append(" select ").append(tableName + TableConst.SEQUENCESUFFIX + ".nextVal").append(",")
                .append("content_id").append(", ")
                .append("content_name").append(", ")
                .append("forum_id").append(", ")
                .append("forum_name").append(", ")
                .append("des").append(", ")
                .append("content_text").append(",")
                .append("update_time").append(",'")
                .append(Flag.STATE_0.getCode()).append("',")
                .append("important").append(",")
                .append("sysdate,'")
                .append(user.getUserId()).append("', '")
                .append(user.getUserName()).append("', ")
                .append("keyWord").append(",")
                .append("submit_time,");
        sql.append("version+1, ");
        String opertype = String.valueOf(param.get("operType"));
        String operActionType = Flag.STATUS_0.getCode(), version = ", version,";
        if (Flag.OPER_3.getCode().equals(opertype)) {
            operActionType = Flag.STATUS_1.getCode();
        }
        sql.append("'").append(operActionType).append("',");
        sql.append("'").append(opertype).append("',")
                .append("file_id").append("");
        sql.append("  from ")
                .append(originTable).append(" where content_id in (")
                .append(param.get("ids")).append(") ");
        sqls.add(sql.toString());
        sql.delete(0, sql.length());
        return sqls;
    }


    /**
     * <p>TODO </p>
     * <p>@param param
     * <p>@return </p>
     *
     * @author : xiaoliu
     * @date :2017年5月27日上午9:08:20
     */
    public String genSysContentUpdateSql(Map<String, Object> param) {
        //表名
        String tableName = String.valueOf(param.get("tableName"));
        //修改数据ID
        String pk = param.get("contentId").toString();

        StringBuilder sql = new StringBuilder();
        SysUser user = ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER);
        String opertype = String.valueOf(param.get("operType"));//操作
        sql.append("update " + tableName + " set ");
        if (Flag.OPER_1.getCode().equals(opertype)) {//变更页面的编辑
            sql.append("UPDATE_TIME = sysdate, ");
            sql.append("OPER_USER = '").append(user.getUserId().longValue())
                    .append("',  OPER_UNAME = '").append(user.getUserName())
                    .append("',  state = ");
            sql.append(Flag.STATE_0.getCode()).append(",");
            sql.append("CONTENT_NAME ='").append((String) param.get("contentName")).append("',");
            sql.append("CONTENT_TEXT ='").append((String) param.get("contentText")).append("',");
            sql.append("FORUM_ID ='").append((String) param.get("forumId")).append("',");
            sql.append("FORUM_NAME ='").append((String) param.get("forumName")).append("',");
            sql.append("DES ='").append((String) param.get("des")).append("',");
            sql.append("IMPORTANT ='").append(param.get("important")).append("' ");
            sql.append(" where CONTENT_ID = ").append(pk);
        } else {//申请页面的编辑方法
            sql.append("UPDATE_TIME = sysdate, ");
            sql.append(" state = ");
            sql.append(Flag.STATE_0.getCode() + ",");
            sql.append("CONTENT_NAME ='").append((String) param.get("contentName")).append("',");
            sql.append("CONTENT_TEXT ='").append((String) param.get("contentText")).append("',");
            sql.append("FORUM_ID ='").append((String) param.get("forumId")).append("',");
            sql.append("FORUM_NAME ='").append((String) param.get("forumName")).append("',");
            sql.append("DES ='").append((String) param.get("des")).append("',");
            sql.append("IMPORTANT ='").append(param.get("important")).append("' ");
            sql.append(" where CONTENT_ID = ").append(pk);
        }
        return sql.toString();
    }

}
